package main
import (
	"www2/cfg"
	"net/http"
	"log"
//	"io/ioutil"
//	"github.com/maxwellhealth/go-enhanced-json"
//	"time"
	"github.com/gorilla/mux"
	"www2/ctl"
	//"www2/sp/cats"
	//"gopkg.in/mgo.v2/bson"
	"github.com/maxwellhealth/bongo"
	//"strings"
	//"io"
	//"gopkg.in/mgo.v2/bson"
	"www2/sp/cats"
	"www2/sp"
)


type testDoc struct{
	ID int
	Bytes []byte
}
func (h *testDoc) AfterFind(c *bongo.Collection) error {
	log.Println(" shtml AfterFind")
	//if h.CT == "" {
	//	h.CT = "text/html; charset=utf-8"
	//}
	return nil
}
type hookedDocument struct {
	bongo.DocumentBase    `bson:",inline"`
	RanBeforeSave   bool
	RanAfterSave    bool
	RanBeforeDelete bool
	RanAfterDelete  bool
	RanAfterFind    bool
}

func (h *hookedDocument) BeforeSave(c *bongo.Collection) error {
	h.RanBeforeSave = true
	return nil
}

func main() {
	//shtml:=&sp.Shtml{}
	////sp.ShtmlBongo.FindById(bson.ObjectIdHex("577df87da3d24b25d97a4bb9"),shtml)
	//sp.ShtmlBongo.FindOne(bson.M{"furl":"https://www.elastic.co/guide/en/elasticsearch/reference/current/search-template.html"},shtml)
	////shtml.AfterFind(sp.ShtmlBongo)
	//log.Println(shtml.CT ,shtml.FUrl)
	//return

	//strings.NewReader()
	//io.Reader()
	//	doc,err:=fc.GetHttpDataWithGzip("
	// ")
	//	log.Println(doc,err)
	//	return
	if *cfg.ConsoleOnly==true{

		if *cfg.ConverTemplate{
			cats.Convertw3Template()
			return
		}
		//if len(*cfg.Durl)>0{
		//
		//}
		var fc *sp.Spider
		if len(*cfg.CatName)>0{
			switch *cfg.CatName{
			case "es":fc=cats.GetEsWebSpider()
			case "mdn":fc=cats.GetMdnWebSpider()
			case "rs":fc=cats.GetRsWebSpider()
			case "w3":fc=cats.Getw3WebSpider()
			}
			if fc!=nil{
				log.Println(fc.Url)
				fc.StartCrawl1(*cfg.ContinueCrawl)
				//esSpider:=cats.Getw3WebSpider();
				//esSpider.StartCrawl1()
			}
			return
		}
	}

	r := mux.NewRouter()
	r.SkipClean(true)

	//s:=r.
	//Host(*cfg.Domian).
	//Subrouter()
	r.HandleFunc("/", ctl.IndexHandler)
	r.HandleFunc("/index.html", ctl.IndexHandler)
	r.HandleFunc("/raw/{path:.*}", ctl.RawHandler)
	r.HandleFunc("/fly/{path:.*}", ctl.FlyHandler)
	r.HandleFunc("/{path:.*}", ctl.ContentHandler)

	//for _,sdomain:=range sp.CDALL{
	//	hostname:=sdomain+"."+ *cfg.Domian
	//	log.Println("init route :",hostname)
	//	ts:=r.
	//	Host(hostname).
	//	Subrouter()
	//	ts.HandleFunc("/raw/{path:.*}", ctl.RawHandler)
	//	ts.HandleFunc("/fly/{path:.*}", ctl.FlyHandler)
	//	ts.HandleFunc("/{path:.*}", ctl.ContentHandler)
	//}
//	r.HandleFunc("/{path:.*}", YourHandler1) //{path:.*}

	log.Println("server will run on ", *cfg.ListenServer)
//	http.Handle("/",r)
//	http.HandleFunc("/", YourHandler1)
	log.Fatal(http.ListenAndServe(*cfg.ListenServer, r))

}

func YourHandler1(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("1Gorilla!\n"+r.URL.Path+" "+r.Host+" string "+r.URL.String()))
}


